package com.example.demo.controller;


import com.example.demo.common.AjaxResult;
import com.example.demo.common.ApplicationVariable;
import com.example.demo.common.PasswordTools;
import com.example.demo.common.UserSessionTools;
import com.example.demo.entity.UserInfo;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/reg")
    public AjaxResult reg(UserInfo userInfo) {
        //前端已经进行非空校验了,后端还是要进行非空校验
        //1.进行非空判断
        if (userInfo == null || !StringUtils.hasLength(userInfo.getUsername())
                || !StringUtils.hasLength(userInfo.getPassword()))
            return AjaxResult.fail(-1, "参数有误");
        //2.调用UserService,执行添加方法,并将返回的结果添加到AjaxResult.data进行返回
        // 将密码进行加盐加密
        userInfo.setPassword(PasswordTools.encrypt(userInfo.getPassword()));
        int result = userService.reg(userInfo);
        return AjaxResult.success(result);
    }

    @RequestMapping("/login")
    public AjaxResult login(String username, String password, HttpServletRequest request) {
        //1.非空校验
        if (!StringUtils.hasLength(username)
                || !StringUtils.hasLength(password))
            return AjaxResult.fail(-1, "参数有误");
        UserInfo userInfo = userService.login(username);
        if (userInfo == null || userInfo.getId() <= 0)
            return AjaxResult.fail(-2, "用户名或密码有误!");
        if (!PasswordTools.decrypt(password, userInfo.getPassword()))
            return AjaxResult.fail(-2, "用户名或密码有误!");
        //将当前成功登录的用户存储到session
        HttpSession session = request.getSession();
        session.setAttribute(ApplicationVariable.SESSION_USERINFO_KEY,userInfo);
        return AjaxResult.success(1);
    }

    /**
     * 退出操作
     * @param request
     * @return
     */
    @RequestMapping("/logout")
    public AjaxResult logout(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        session.removeAttribute(ApplicationVariable.SESSION_USERINFO_KEY);
        return AjaxResult.success(1);
    }

    /**
     *判断当前用户是否已经登录
     * @param request
     * @return
     */
    @RequestMapping("/islogin")
    public AjaxResult isLogin(HttpServletRequest request){
        if (UserSessionTools.getLoginUser(request)==null){
            return AjaxResult.success(0);
        }else {
            return AjaxResult.success(1);
        }
    }
}
